package dtos

import (
	"github.com/edgexfoundry/edgex-go/internal/app/models"
	"github.com/edgexfoundry/go-mod-core-contracts/v2/dtos"
	"strings"
)

type Device struct {
	dtos.Device  `json:",inline"`
	RegisterTime string      `json:"registerTime"`
	NodeType     int         `json:"nodeType"` //1 设备 2 网关
	Enable       bool        `json:"enable"`
	Code         string      `json:"code"`
	ProductId    string      `json:"productId"`
	ProfileId    string      `json:"profileId"`
	Labels       string      `json:"labels"`
	ProductName  string      `json:"productName"`
	DisplayName  string      `json:"displayName"`
	AutoEvents   []AutoEvent `json:"autoEvents"`
}

type AutoEvent struct {
	dtos.AutoEvent `json:",inline"`
	Id             string `json:"id"`
	SourceCode     string `json:"sourceCode"`
	SourceType     int    `json:"sourceType"`
}

type Transport struct {
	Id          string `json:"id,omitempty"`
	Name        string `json:"name,omitempty"`
	Type        string `json:"type,omitempty"`
	Topic       string `json:"topic,omitempty"`
	Description string `json:"description,omitempty"`
}

type DeviceCount struct {
	Total   uint32 `json:"total"`
	Online  uint32 `json:"online"`
	Offline uint32 `json:"offline"`
}

func (d *Device) ToDeviceModel() models.Device {
	ls := strings.Split(d.Labels, ",")
	d.Device.Labels = ls
	return models.Device{
		Device:       dtos.ToDeviceModel(d.Device),
		RegisterTime: d.RegisterTime,
		NodeType:     d.NodeType,
		Enable:       d.Enable,
		Code:         d.Code,
		ProductId:    d.ProductId,
		ProfileId:    d.ProfileId,
		ProductName:  d.ProductName,
		DisplayName:  d.DisplayName,
		AutoEvents:   ToAutoEventModels(d.AutoEvents),
	}
}

func (a *AutoEvent) ToAutoEventModel() models.AutoEvent {
	return models.AutoEvent{
		Id:         a.Id,
		SourceCode: a.SourceCode,
		SourceType: a.SourceType,
		AutoEvent:  dtos.ToAutoEventModel(a.AutoEvent),
	}
}

func ToAutoEventModels(aes []AutoEvent) []models.AutoEvent {
	autoEvents := make([]models.AutoEvent, len(aes))
	for index, ae := range aes {
		autoEvents[index] = ae.ToAutoEventModel()
	}
	return autoEvents
}

func (a *Transport) ToTransportModel() models.Transport {
	return models.Transport{
		Id:          a.Id,
		Name:        a.Name,
		Type:        a.Type,
		Topic:       a.Topic,
		Description: a.Description,
	}
}

func ToTransportModels(ts []Transport) []models.Transport {
	transports := make([]models.Transport, len(ts))
	for index, t := range ts {
		transports[index] = t.ToTransportModel()
	}
	return transports
}

func (c *DeviceCount) ToDeviceCountModel() models.DeviceCount {
	return models.DeviceCount{
		Total:   c.Total,
		Online:  c.Online,
		Offline: c.Offline,
	}
}
